package com.museum.guide.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.museum.guide.entity.AppointmentTimeSlot;
import com.museum.guide.mapper.AppointmentTimeSlotMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AppointmentTimeSlotService extends ServiceImpl<AppointmentTimeSlotMapper, AppointmentTimeSlot> {

    /**
     * 分页查询时间段信息
     */
    public Page<AppointmentTimeSlot> page(Page<AppointmentTimeSlot> page, String name, String period, Integer status) {
        LambdaQueryWrapper<AppointmentTimeSlot> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), AppointmentTimeSlot::getName, name)
                .eq(StringUtils.hasText(period), AppointmentTimeSlot::getPeriod, period)
                .eq(status != null, AppointmentTimeSlot::getStatus, status)
                .orderByAsc(AppointmentTimeSlot::getStartTime);
        return page(page, wrapper);
    }

    /**
     * 获取所有可用的时间段列表
     */
    public List<AppointmentTimeSlot> listEnabled() {
        LambdaQueryWrapper<AppointmentTimeSlot> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppointmentTimeSlot::getStatus, 1)
                .orderByAsc(AppointmentTimeSlot::getStartTime);
        return list(wrapper);
    }

    /**
     * 根据时段获取时间段列表
     */
    public List<AppointmentTimeSlot> listByPeriod(String period) {
        LambdaQueryWrapper<AppointmentTimeSlot> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppointmentTimeSlot::getPeriod, period)
                .eq(AppointmentTimeSlot::getStatus, 1)
                .orderByAsc(AppointmentTimeSlot::getStartTime);
        return list(wrapper);
    }

    /**
     * 新增时间段
     */
    public void saveTimeSlot(AppointmentTimeSlot timeSlot) {
        timeSlot.setCreateTime(LocalDateTime.now());
        timeSlot.setUpdateTime(LocalDateTime.now());
        save(timeSlot);
    }

    /**
     * 更新时间段信息
     */
    public void updateTimeSlot(AppointmentTimeSlot timeSlot) {
        timeSlot.setUpdateTime(LocalDateTime.now());
        updateById(timeSlot);
    }

    /**
     * 删除时间段
     */
    public void removeTimeSlot(Long id) {
        removeById(id);
    }

    /**
     * 启用/禁用时间段
     */
    public void updateStatus(Long id, Integer status) {
        AppointmentTimeSlot timeSlot = getById(id);
        if (timeSlot != null) {
            timeSlot.setStatus(status);
            timeSlot.setUpdateTime(LocalDateTime.now());
            updateById(timeSlot);
        }
    }
}